package com.apexedu.sync.engine.impl;

import com.apexedu.framework.util.DBUtil;
import com.apexedu.identity.entity.TSysUser;
import com.apexedu.portal.util.LittleTimer;
import com.apexedu.sync.engine.ISyncContext;
import com.apexedu.sync.engine.ISyncEngine;
import com.apexedu.sync.exception.AuCSyncException;
import com.apexedu.sync.node.ISyncNode;
import com.apexedu.sync.node.impl.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 同步Apexssh系统数据到角色权限中心
 * Created by ly on 2015/1/12.
 */
public class SyncEngine implements ISyncEngine {
    private static final Log LOG = LogFactory.getLog(SyncEngine.class);//日志记录

    /**
     * 用户集合 <用户登录账号，用户对象>
     * 所有系统都通用，放在引擎中
     */
    private Map<String, TSysUser> mapUser = new HashMap<String, TSysUser>();

    public SyncEngine() {
        build();
    }

    public void build() {
        List<TSysUser> userList = DBUtil.queryAllBeanList("select * from T_Sys_User where state != 0", TSysUser.class);
        for (TSysUser user : userList) {
            mapUser.put(user.getUserloginid(), user);
        }
    }

    @Override
    public void execute(ISyncContext context) throws AuCSyncException {
        List<ISyncNode> listNode = new ArrayList<ISyncNode>();
        if (context.isLivebos()) { //livebos系统
            listNode.add(new LivebosUserNode());//同步用户
            listNode.add(new RoleNode()); //同步角色
            listNode.add(new UserRoleNode()); //同步用户角色关系
            listNode.add(new LivebosMenuNode()); //同步菜单资源
            listNode.add(new RoleMenuNode()); //同步角色菜单关联关系
        } else if (context.isApexssh()) {
            listNode.add(new RoleNode()); //同步角色
            listNode.add(new UserRoleNode());//同步用户角色关系
            listNode.add(new ApexsshMenuNode());//同步菜单资源
            listNode.add(new RoleMenuNode());//同步角色菜单关联关系
        }
        context.getMsg().setAppname(context.getAccessAppReg().getAppname());
        for (int i = 0; i < listNode.size(); i++) {
            try {
                ISyncNode node = listNode.get(i);
                LittleTimer timer = new LittleTimer();
                timer.start();
                node.execute(context);
                LOG.debug("<<" + node.getClass().getSimpleName() + ">> " + timer.end());
            } catch (AuCSyncException e) {
                break;
            }
        }
    }

    @Override
    public Map<String, TSysUser> getMapUser() {
        return mapUser;
    }
}
